package com.snapp.web.agents;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.jdom.Element;
import org.jdom.JDOMException;

import com.snapp.util.Bean;
import com.snapp.util.object.model.ObjectModel;

public class AccessAgent extends SNAppAgent {
	private static Logger logger = Logger.getLogger(AccessAgent.class);
	
	public ObjectModel login(HashMap<String, String> params) {
		ObjectModel acc = null;
		try {
			// load access object based on given user id and password
			ObjectModel creds = load("SNAPP_USER_CREDS", params);
			// check results..
			if (creds.getBean() == null) {
				return null;
			}
			
			// load user
			acc = load("SNAPP_USER", "id="+creds.getBean().getPropertyString("userid")+" and status=1");
			
			// load user permissions
			Vector<ObjectModel> perms = list("SNAPP_USER_PERM", "userid="+acc.getBean().getPropertyString("id")+" order by seq");
			
			// prepare permit hashmap..
			HashMap<String,String> permits = new HashMap<String, String>();
			
			Iterator<ObjectModel> itr = perms.iterator();
			while (itr.hasNext()) {
				Bean nxt = itr.next().getBean();
				// add to security permits
				permits.put(nxt.getPropertyString("mnemonic"), Integer.toString(nxt.hashCode()));
				logger.info("Adding User Functon:  "+nxt.getPropertyString("mnemonic") + " > " + Integer.toString(nxt.hashCode()));
			}
			
			// add permits to user access
			acc.getBean().setProperty("permits", permits, "permits");
		
			// load user functions
			Vector<ObjectModel> functs = list("SNAPP_USER_FUNCTION","userid = "+creds.getBean().getPropertyString("userid"));
			acc.getBean().setProperty("functions",functs,"functions");
			
			// track login
			HashMap<String, String> loginrec = new HashMap<String, String>();
			loginrec.put("userid", acc.getBean().getPropertyString("id"));
			// save record
			//ObjectModel rec = save("SNAPP_LOGINREC", loginrec);
			// set record id for function tracking
			//acc.getBean().setProperty("loginrecid", rec.getBean().getPropertyString("id"),rec.getBean().getPropertyString("id"));
	
		} catch(Exception e) {
			acc = null;
			logger.error("Error attempting login",e);
		}
		return acc;
	}
	
	/**
	 * Sort the flat list of functions by moving children under the parents..
	 * @param fs
	 * @return
	 */
	public Element sortFunctionTree(Vector<ObjectModel> flist, String parent, Element pEl) {
		if (pEl == null)
			pEl = new Element("functions");
		
		logger.info("adding content for parent: "+parent+ " > name: " + pEl.getName());
		// parent list..
		Iterator<ObjectModel> itr = flist.iterator();
		while (itr.hasNext()) {
			
			ObjectModel nxt = itr.next();
			if (nxt.getBean().getPropertyString("parent").equals(parent)) {
				logger.info("Adding child of "+parent+".  ID is "+nxt.getBean().getPropertyString("id"));
				Element nel = null;
				try {
					nel = nxt.getBean().toXML();
					pEl.addContent(nel);
				} catch (JDOMException e) {
					logger.warn("Could not parse user function to xml.",e);
				}
				
				sortFunctionTree(flist, nxt.getBean().getPropertyString("id"), nel);
			}
		}
		
		return pEl;
	}
	
}
